extends TileMap


var tile_cfg: Dictionary = {
	"normal": {"health": 1.0},
	"cement": {
		"health": 6.0,
		"stage": [
			{"range": [6.0, 4.0], "atlas_coords": Vector2i(4, 1), "source_id": 0},
			{"range": [4.0, 2.0], "atlas_coords": Vector2i(6, 1), "source_id": 0},
			{"range": [2.0, 0.0], "atlas_coords": Vector2i(8, 1), "source_id": 0}
		]
	},
	"metal": {"health": -1.0},
	"tree": {"health": 1.0},
}

var tile_health: Dictionary = {}


func body_entered(body_rid: RID, body: TileMap, from: Node2D) -> void:
	var coords: Vector2i = body.get_coords_for_body_rid(body_rid)
	var tile_data : TileData = body.get_cell_tile_data(0, coords)
	if tile_data:
		var type : String = tile_data.get_custom_data("type")
		if type:
			var cfg : Dictionary = tile_cfg[type]
			if cfg["health"] > 0:
				if cfg["health"] <= from.damage: 
					body.erase_cell(0, coords)
				else:
					var key := body_rid
					tile_health[key] = (cfg["health"] - from.damage) if not tile_health.has(key) else (tile_health[key] - from.damage)
					if tile_health[key] <= 0:
						body.erase_cell(0, coords)
						tile_health.erase(key)
					elif cfg.has("stage"):
						var atlas_coords := body.get_cell_atlas_coords(0, coords)
						for s in cfg.stage:
							if tile_health[key] <= s.range[0] and tile_health[key] > s.range[1] and s["atlas_coords"] != atlas_coords:
								body.set_cell(0, coords, s["source_id"], s["atlas_coords"])






